from flask import Blueprint, render_template, jsonify, request
from models.entity.sensor_type import SensorType
from models.entity.sensor import Sensor
import json

mod = Blueprint("iot_sensor_type", __name__, url_prefix="/iot/sensor_type", template_folder="templates",
                static_folder="static")


@mod.route("/", methods=["GET"])
def iot_sensor_type_index(*args, **kargs):
    return render_template('/admin/iot/iot_sensor_type_index.html', **locals())

@mod.route('/add/', methods=["GET", 'POST'])
def add_type():
    """增加传感器类型"""
    """
    {
    "name":"光线传感器",
    "code":"256412X",
    "description":"wu",
    "sensor_type_id":1,
    "sensor_group_id":1,
    "device_id":1,
    "dis_order":1
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "name is null"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name']
        if "code" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "code is null"
            tmp['data'] = data
            return jsonify(tmp)
        code = dict['code']
        # description = dict['description']
        # dis_order = dict['dis_order']
        # icon=dict['icon']
        sensor_type = SensorType()
        if SensorType.query.filter_by(name=name).first() is not None:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "name exists"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type.name = name
        if SensorType.query.filter_by(code=code).first() is not None:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "code exists"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type.code = code
        # sensor_type.dis_order = (dis_order)
        # sensor_type.description = description
        # sensor_type.icon=icon
        if sensor_type.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unknown error"
            tmp['data'] = data
            return jsonify(tmp)
    else:
        # print(22233333)
        return ('222rrr')



@mod.route('/edit/', methods=['GET', 'POST'])
def edit_device_type():
    """编辑传感器类型"""
    """
    {
    "id":1,
    "name":"气器",
    "code":"HDKddL",
    "description":"wu",
    "dis_order":2
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']
        sensor_type = SensorType.query.filter_by(id=id).first()
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "name is null"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name']
        if "code" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "code is null"
            tmp['data'] = data
            return jsonify(tmp)
        code = dict['code']
        if "description" in dict:
            description = dict['description']
        else:
            description = None
        if "icon" in dict:
            icon=dict['icon']
        else:
            icon=None
        dis_order = dict['dis_order']

        if name != sensor_type.name and SensorType.query.filter_by(name=name).first():
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "name exist"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type.name = name
        if code != sensor_type.code and SensorType.query.filter_by(code=code).first():
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "code exist"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type.code = code
        sensor_type.description = description
        sensor_type.dis_order = dis_order
        sensor_type.icon=icon

        if sensor_type.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -4
            tmp['error_msg'] = "unknown error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_device_type():
    """删除传感器类型"""
    """
    {
    "id":1
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = dict['id']

        if Sensor.query.filter_by(sensor_type_id=id).first():
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "该传感器类型下还有传感器，不能删除"
            tmp['data'] = data
            return jsonify(tmp)
        sensor_type = SensorType.query.filter_by(id=id).first()
        if sensor_type.delete():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "unknown error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_device_type():
    """获取所有传感器类型"""
    """
        无需传入参数
    """
    tmp = {}
    data = []
    sensor_types = SensorType.query.all()
    for item in sensor_types:
        tdic=item.to_dict()
        tdic["sensor_number"]=len(Sensor.query.filter_by(sensor_type_id = item.id).all())
        data.append(tdic)
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)

@mod.route("/search/",methods=["GET", "POST"])
def search_sensor_type():
    """
    模糊查询
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.data
        data = json.loads(receive.decode("utf-8"))
        tmp ={}
        extra =[]
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            tmp['success'] = 0
            tmp['error_code'] = -9
            tmp['error_msg'] = "数据格式错误"
            tmp['data'] = extra
            return jsonify(tmp)
        sensor_types = SensorType.search(query_word)
        return jsonify(sensor_types)